package com.sxfq.loansupermarket.backsystem.modular.system.controller;

import com.google.code.kaptcha.Constants;
import com.sxfq.loansupermarket.backsystem.common.constant.state.ManagerStatus;
import com.sxfq.loansupermarket.backsystem.common.controller.BaseController;
import com.sxfq.loansupermarket.backsystem.common.exception.BizExceptionEnum;
import com.sxfq.loansupermarket.backsystem.common.exception.BussinessException;
import com.sxfq.loansupermarket.backsystem.common.exception.InvalidKaptchaException;
import com.sxfq.loansupermarket.backsystem.common.persistence.dao.UserMapper;
import com.sxfq.loansupermarket.backsystem.common.persistence.model.User;
import com.sxfq.loansupermarket.backsystem.core.log.LogManager;
import com.sxfq.loansupermarket.backsystem.core.log.factory.LogTaskFactory;
import com.sxfq.loansupermarket.backsystem.core.shiro.ShiroKit;
import com.sxfq.loansupermarket.backsystem.core.shiro.ShiroUser;
import com.sxfq.loansupermarket.backsystem.core.support.HttpKit;
import com.sxfq.loansupermarket.backsystem.core.util.StringUtil;
import com.sxfq.loansupermarket.backsystem.core.util.ToolUtil;
import com.sxfq.loansupermarket.backsystem.modular.base.SqlMapper;
import com.sxfq.loansupermarket.backsystem.modular.system.dao.MenuDao;
import com.sxfq.loansupermarket.backsystem.modular.system.dao.UserMgrDao;
import com.sxfq.loansupermarket.backsystem.modular.system.factory.UserFactory;
import com.sxfq.loansupermarket.backsystem.modular.system.transfer.UserDto;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 登录控制器
 *
 * @author fengshuonan
 * @Date 2017年1月10日 下午8:25:24
 */
@Controller
public class LoginController extends BaseController {
    @Resource
    private UserMgrDao managerDao;

    @Autowired
    MenuDao menuDao;

    @Autowired
    UserMapper userMapper;

    @Autowired
    UserMgrDao userMgrDao;

    @Autowired
    private SqlMapper sqlMapper;

    /**
     * 跳转到主页
     */
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String index(Model model) {
//        //获取菜单列表
//        List<Integer> roleList = ShiroKit.getUser().getRoleList();
//        if (roleList == null || roleList.size() == 0) {
//            ShiroKit.getSubject().logout();
//            model.addAttribute("tips", "该用户没有角色，无法登陆");
//            return "/login.html";
//        }
//        List<MenuNode> menus = menuDao.getMenusByRoleIds(roleList);
//        List<MenuNode> titles = MenuNode.buildTitle(menus);
//        model.addAttribute("titles", titles);
//        //获取用户头像
//        Integer id = ShiroKit.getUser().getId();
//        User user = userMapper.selectById(id);
//        String avatar = user.getAvatar();
//        model.addAttribute("avatar", avatar);
//        model.addAttribute("userName", user.getName());
//        model.addAttribute("time", DateTimeKit.now());
//        String sql = " select  a.the_test_score ,a.name from user a order by a.the_test_score desc";
//        List<UserDto> list = sqlMapper.selectList(sql, UserDto.class);
//        String oneName = list.get(0).getName();
//        String twoName = list.get(1).getName();
//        String tirName = list.get(2).getName();
//        String fourName = list.get(3).getName();
//        String fiveName = list.get(4).getName();
//        String sixName = list.get(list.size()-1).getName();
        String sql1 = "select a.the_test_score from user a group by a.the_test_score order by a.the_test_score desc limit 0,3";
        List<UserDto> orderByScoreList = sqlMapper.selectList(sql1, UserDto.class);
        String sql = "  select t.the_test_score ,t.name,t.avatar,(select count(s.the_test_score)+1 from user s where s.the_test_score>t.the_test_score) rank from user t order by t.the_test_score desc;";
        List<UserDto> list = sqlMapper.selectList(sql, UserDto.class);
        List<UserDto> list1 = new ArrayList<UserDto>();
        for (UserDto dto : list) {
            if (dto.getRank() == 1) {
                dto.setTitleName("学神");
            } else if (dto.getRank() == 2) {
                dto.setTitleName("学霸");
            } else if (dto.getRank() == 3) {
                dto.setTitleName("学长");
            } else if (dto.getRank() == list.get(list.size() - 1).getRank()) {
                dto.setTitleName("学灰");
            } else {
                dto.setTitleName("学员");
            }
            if (dto.getName().length() > 3) {
                dto.setName(dto.getName().substring(0, 3));
            }
            if (dto.getAvatar() == null || dto.getAvatar() == "") {
                dto.setAvatar("http://yiyayl.com/photo/logo.png");
            }
            list1.add(dto);
        }
        model.addAttribute("oneName", list1.get(0).getName());
        model.addAttribute("oneScore", list1.get(0).getTheTestScore());
        model.addAttribute("oneTitleName", list1.get(0).getTitleName());
        model.addAttribute("oneAvatar", list1.get(0).getAvatar());

        model.addAttribute("twoName", list1.get(1).getName());
        model.addAttribute("twoScore", list1.get(1).getTheTestScore());
        model.addAttribute("twoTitleName", list1.get(1).getTitleName());
        model.addAttribute("twoAvatar", list1.get(1).getAvatar());

        model.addAttribute("tirName", list1.get(2).getName());
        model.addAttribute("tirScore", list1.get(2).getTheTestScore());
        model.addAttribute("tirTitleName", list1.get(2).getTitleName());
        model.addAttribute("tirAvatar", list1.get(2).getAvatar());

        model.addAttribute("fourName", list1.get(3).getName());
        model.addAttribute("fourScore", list1.get(3).getTheTestScore());
        model.addAttribute("fourTitleName", list1.get(3).getTitleName());
        model.addAttribute("fourAvatar", list1.get(3).getAvatar());

        model.addAttribute("fiveName", list1.get(4).getName());
        model.addAttribute("fiveScore", list1.get(4).getTheTestScore());
        model.addAttribute("fiveTitleName", list1.get(4).getTitleName());
        model.addAttribute("fiveAvatar", list1.get(4).getAvatar());

        model.addAttribute("sixName", list1.get(list.size() - 1).getName());
        model.addAttribute("sixScore", list1.get(list.size() - 1).getTheTestScore());
        model.addAttribute("sixTitleName", list1.get(list.size() - 1).getTitleName());
        model.addAttribute("sixAvatar", list1.get(list.size() - 1).getAvatar());
        return "/index.html";
    }

    /**
     * 跳转到主页
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String indexIndex(Model model) {
//        Integer id = ShiroKit.getUser().getId();
//        User user = userMapper.selectById(id);
//        model.addAttribute("userName", user.getName());
//        model.addAttribute("time", DateTimeKit.now());
        String sql = "  select t.the_test_score ,t.name,t.avatar,(select count(s.the_test_score)+1 from user s where s.the_test_score>t.the_test_score) rank from user t order by t.the_test_score desc;";
        List<UserDto> list = sqlMapper.selectList(sql, UserDto.class);
        List<UserDto> list1 = new ArrayList<UserDto>();
        for (UserDto dto : list) {
            if (dto.getRank() == 1) {
                dto.setTitleName("学神");
            } else if (dto.getRank() == 2) {
                dto.setTitleName("学霸");
            } else if (dto.getRank() == 3) {
                dto.setTitleName("学长");
            } else if (dto.getRank() == list.get(list.size() - 1).getRank()) {
                dto.setTitleName("学灰");
            } else {
                dto.setTitleName("学员");
            }
            if (dto.getName().length() > 3) {
                dto.setName(dto.getName().substring(0, 3));
            }
            if (dto.getAvatar() == null || dto.getAvatar() == "") {
                dto.setAvatar("http://yiyayl.com/photo/logo.png");
            }
            list1.add(dto);
        }
        model.addAttribute("oneName", list1.get(0).getName());
        model.addAttribute("oneScore", list1.get(0).getTheTestScore());
        model.addAttribute("oneTitleName", list1.get(0).getTitleName());
        model.addAttribute("oneAvatar", list1.get(0).getAvatar());

        model.addAttribute("twoName", list1.get(1).getName());
        model.addAttribute("twoScore", list1.get(1).getTheTestScore());
        model.addAttribute("twoTitleName", list1.get(1).getTitleName());
        model.addAttribute("twoAvatar", list1.get(1).getAvatar());

        model.addAttribute("tirName", list1.get(2).getName());
        model.addAttribute("tirScore", list1.get(2).getTheTestScore());
        model.addAttribute("tirTitleName", list1.get(2).getTitleName());
        model.addAttribute("tirAvatar", list1.get(2).getAvatar());

        model.addAttribute("fourName", list1.get(3).getName());
        model.addAttribute("fourScore", list1.get(3).getTheTestScore());
        model.addAttribute("fourTitleName", list1.get(3).getTitleName());
        model.addAttribute("fourAvatar", list1.get(3).getAvatar());

        model.addAttribute("fiveName", list1.get(4).getName());
        model.addAttribute("fiveScore", list1.get(4).getTheTestScore());
        model.addAttribute("fiveTitleName", list1.get(4).getTitleName());
        model.addAttribute("fiveAvatar", list1.get(4).getAvatar());

        model.addAttribute("sixName", list1.get(list.size() - 1).getName());
        model.addAttribute("sixScore", list1.get(list.size() - 1).getTheTestScore());
        model.addAttribute("sixTitleName", list1.get(list.size() - 1).getTitleName());
        model.addAttribute("sixAvatar", list1.get(list.size() - 1).getAvatar());
        return "/index.html";
    }

    /**
     * 跳转到登录页面
     */
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login() {
        if (!StringUtil.isEmpty(ShiroKit.getUser())) {
            return REDIRECT + "/testMenu";
        } else {
            return "/login.html";
        }
    }

    /**
     * 跳转到注册页面
     */
    @RequestMapping(value = "/register", method = RequestMethod.GET)
    public String register() {
        return "/register.html";
    }

    /**
     * 跳转到注册页面
     */
    @RequestMapping(value = "/registers", method = RequestMethod.GET)
    public String registers() {
        return "/registers.html";
    }

    /**
     * 点击登录执行的动作s
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String loginVali() {
        String username = super.getPara("username").trim();
        String password = super.getPara("password").trim();
        //验证验证码是否正确
//        if (ToolUtil.getKaptchaOnOff()) {
//        String kaptcha = super.getPara("kaptcha").trim();
//        String code = (String) super.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
//        if (ToolUtil.isEmpty(kaptcha) || !kaptcha.equals(code)) {
//            throw new InvalidKaptchaException();
//        }
//        }
        Subject currentUser = ShiroKit.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password.toCharArray());
        token.setRememberMe(true);
        currentUser.login(token);

        ShiroKit.setSessionAttr("tokens", token);
        ShiroKit.setSessionAttr("tokenss", ShiroKit.getSessionAttr("tokens") + token.toString());
        String aa = ShiroKit.getSessionAttr("tokens").toString();
        System.out.println(aa);
//        RedisUtil.setex(token.toString(), username, UserConstant.EXPIRED_TIME);
        ShiroUser shiroUser = ShiroKit.getUser();
        super.getSession().setAttribute("shiroUser", shiroUser);
        super.getSession().setAttribute("username", shiroUser.getAccount());
        LogManager.me().executeLog(LogTaskFactory.loginLog(shiroUser.getId(), HttpKit.getIp()));
        ShiroKit.getSession().setAttribute("sessionFlag", true);
        return REDIRECT + "/";
    }

    /**
     * 点击登录执行的动作s
     */
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    @ResponseBody
    public String register_add() {
        UserDto user = new UserDto();
        String userName = super.getPara("userName").trim();
        String passWord = super.getPara("passWord").trim();
        String rePassWord = super.getPara("rePassWord").trim();
        user.setAccount(userName);
        user.setRoleid("26");
        user.setName(userName);
        user.setPassword(passWord);
        user.setSalt(ShiroKit.getRandomSalt(5));
        // 判断账号是否重复
        User theUser = managerDao.getByAccount(user.getAccount());
        if (theUser != null) {
            throw new BussinessException(BizExceptionEnum.USER_ALREADY_REG);
        }
        user.setPassword(ShiroKit.md5(user.getPassword(), user.getSalt()));
        user.setStatus(ManagerStatus.OK.getCode());
        user.setCreatetime(new Date());
        this.userMapper.insert(UserFactory.createUser(user));
        return REDIRECT + "/";
    }

    /**
     * 点击登录执行的动作s
     */
    @RequestMapping(value = "/registers", method = RequestMethod.POST)
    @ResponseBody
    public String registers_add() {
        UserDto user = new UserDto();
        String userName = super.getPara("userName").trim();
        String passWord = super.getPara("passWord").trim();
        String rePassWord = super.getPara("rePassWord").trim();
        user.setAccount(userName);
        user.setRoleid("25");
        user.setName(userName);
        user.setPassword(passWord);
        user.setSalt(ShiroKit.getRandomSalt(5));
        // 判断账号是否重复
        User theUser = managerDao.getByAccount(user.getAccount());
        if (theUser != null) {
            throw new BussinessException(BizExceptionEnum.USER_ALREADY_REG);
        }
        user.setPassword(ShiroKit.md5(user.getPassword(), user.getSalt()));
        user.setStatus(ManagerStatus.OK.getCode());
        user.setCreatetime(new Date());
        this.userMapper.insert(UserFactory.createUser(user));
        return REDIRECT + "/";
    }

    /**
     * 退出登录
     */
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public String logOut(HttpServletRequest request, HttpServletResponse response, Object handler) {
        ShiroUser ss = ShiroKit.getUser();
        LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
        ShiroKit.getSubject().logout();
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        return REDIRECT + "/index";
    }
}
